package org.example.finaspringboot.service.serviceiml;

import org.example.finaspringboot.entity.User;

public class UserService {
    public User register(User newUser) {
        // Hash the password before storing it in the database
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        newUser.setPassword(encoder.encode(newUser.getPassword()));
        userMapper.insert(newUser);
        return newUser;
    }

    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user != null && new BCryptPasswordEncoder().matches(password, user.getPassword())) {
            return user;
        }
        return null; // Login failed
    }

    public boolean changePassword(Integer userId, String oldPassword, String newPassword) {
        User user = userMapper.findByUsername(null); // Need to find by ID instead
        if (user != null && new BCryptPasswordEncoder().matches(oldPassword, user.getPassword())) {
            user.setId(userId);
            user.setPassword(new BCryptPasswordEncoder().encode(newPassword));
            return userMapper.updatePassword(user) > 0;
        }
        return false;
    }
}
